documentation for BacklinkCache class
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2 /**
3 * File for BacklinkCache class
4 * @file
5 */
6
7 /**
8 * Class for fetching backlink lists, approximate backlink counts and
9 * partitions. This is a shared cache.
10 *
11 * Instances of this class should typically be fetched with the method
12 * $title->getBacklinkCache().
13 *
14 * Ideally you should only get your backlinks from here when you think
15 * there is some advantage in caching them. Otherwise it's just a waste
16 * of memory.
17 *
18 * Introduced by r47317
19 *
20 * @internal documentation reviewed on 18 Mar 2011 by hashar
21 *
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Ashar Voultoiz
26 */
27 class BacklinkCache {
28
29 /**
30 * Multi dimensions array representing batches. Keys are:
31 * > (string) links table name
32 * > 'numRows' : Number of rows for this link table
33 * > 'batches' : array( $start, $end )
34 *
35 * @see BacklinkCache::partitionResult()
36 * @todo Should be private
37 *
38 * Cleared with BacklinkCache::clear()
39 */
40 var $partitionCache = array();
41
42 /**
43 * Contains the whole links from a database result.
44 * This is raw data that will be partitioned in $partitionCache
45 *
46 * @todo Should be private
47 *
48 * Initialized with BacklinkCache::getLinks()
49 * Cleared with BacklinkCache::clear()
50 */
51 var $fullResultCache = array();
52
53 /**
54 * Local copy of a database object.
55 *
56 * Accessor: BacklinkCache::getDB()
57 * Mutator : BacklinkCache::setDB()
58 * Cleared with BacklinkCache::clear()
59 *
60 * @todo Should be private
61 */
62 var $db;
63
64 /**
65 * Local copy of a Title object
66 * @todo Should be private
67 */
68 var $title;
69
70 const CACHE_EXPIRY = 3600;
71
72 /**
73 * Create a new BacklinkCache
74 * @param Title $title : Title object to create a backlink cache for.
75 */
76 function __construct( $title ) {
77 $this->title = $title;
78 }
79
80 /**
81 * Serialization handler, diasallows to serialize the database to prevent
82 * failures after this class is deserialized from cache with dead DB
83 * connection.
84 */
85 function __sleep() {
86 return array( 'partitionCache', 'fullResultCache', 'title' );
87 }
88
89 /**
90 * Clear locally stored data and database object.
91 */
92 function clear() {
93 $this->partitionCache = array();
94 $this->fullResultCache = array();
95 unset( $this->db );
96 }
97
98 /**
99 * Set the Database object to use
100 */
101 public function setDB( $db ) {
102 $this->db = $db;
103 }
104
105 /**
106 * Get the slave connection to the database
107 * When non existing, will initialize the connection.
108 * @return Database object
109 */
110 protected function getDB() {
111 if ( !isset( $this->db ) ) {
112 $this->db = wfGetDB( DB_SLAVE );
113 }
114
115 return $this->db;
116 }
117
118 /**
119 * Get the backlinks for a given table. Cached in process memory only.
120 * @param $table String
121 * @param $startId Integer or false
122 * @param $endId Integer or false
123 * @return TitleArray
124 */
125 public function getLinks( $table, $startId = false, $endId = false ) {
126 wfProfileIn( __METHOD__ );
127
128 $fromField = $this->getPrefix( $table ) . '_from';
129
130 if ( $startId || $endId ) {
131 // Partial range, not cached
132 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
133 $conds = $this->getConditions( $table );
134
135 // Use the from field in the condition rather than the joined page_id,
136 // because databases are stupid and don't necessarily propagate indexes.
137 if ( $startId ) {
138 $conds[] = "$fromField >= " . intval( $startId );
139 }
140
141 if ( $endId ) {
142 $conds[] = "$fromField <= " . intval( $endId );
143 }
144
145 $res = $this->getDB()->select(
146 array( $table, 'page' ),
147 array( 'page_namespace', 'page_title', 'page_id' ),
148 $conds,
149 __METHOD__,
150 array(
151 'STRAIGHT_JOIN',
152 'ORDER BY' => $fromField
153 ) );
154 $ta = TitleArray::newFromResult( $res );
155
156 wfProfileOut( __METHOD__ );
157 return $ta;
158 }
159
160 // FIXME : make this a function?
161 if ( !isset( $this->fullResultCache[$table] ) ) {
162 wfDebug( __METHOD__ . ": from DB\n" );
163 $res = $this->getDB()->select(
164 array( $table, 'page' ),
165 array( 'page_namespace', 'page_title', 'page_id' ),
166 $this->getConditions( $table ),
167 __METHOD__,
168 array(
169 'STRAIGHT_JOIN',
170 'ORDER BY' => $fromField,
171 ) );
172 $this->fullResultCache[$table] = $res;
173 }
174
175 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
176
177 wfProfileOut( __METHOD__ );
178 return $ta;
179 }
180
181 /**
182 * Get the field name prefix for a given table
183 * @param $table String
184 */
185 protected function getPrefix( $table ) {
186 static $prefixes = array(
187 'pagelinks' => 'pl',
188 'imagelinks' => 'il',
189 'categorylinks' => 'cl',
190 'templatelinks' => 'tl',
191 'redirect' => 'rd',
192 );
193
194 if ( isset( $prefixes[$table] ) ) {
195 return $prefixes[$table];
196 } else {
197 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
198 }
199 }
200
201 /**
202 * Get the SQL condition array for selecting backlinks, with a join
203 * on the page table.
204 * @param $table String
205 */
206 protected function getConditions( $table ) {
207 $prefix = $this->getPrefix( $table );
208
209 // FIXME imagelinks and categorylinks do not rely on getNamespace,
210 // they could be moved up for nicer case statements
211 switch ( $table ) {
212 case 'pagelinks':
213 case 'templatelinks':
214 case 'redirect':
215 $conds = array(
216 "{$prefix}_namespace" => $this->title->getNamespace(),
217 "{$prefix}_title" => $this->title->getDBkey(),
218 "page_id={$prefix}_from"
219 );
220 break;
221 case 'imagelinks':
222 $conds = array(
223 'il_to' => $this->title->getDBkey(),
224 'page_id=il_from'
225 );
226 break;
227 case 'categorylinks':
228 $conds = array(
229 'cl_to' => $this->title->getDBkey(),
230 'page_id=cl_from',
231 );
232 break;
233 default:
234 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
235 }
236
237 return $conds;
238 }
239
240 /**
241 * Get the approximate number of backlinks
242 * @param $table String
243 * @return integer
244 */
245 public function getNumLinks( $table ) {
246 if ( isset( $this->fullResultCache[$table] ) ) {
247 return $this->fullResultCache[$table]->numRows();
248 }
249
250 if ( isset( $this->partitionCache[$table] ) ) {
251 $entry = reset( $this->partitionCache[$table] );
252 return $entry['numRows'];
253 }
254
255 $titleArray = $this->getLinks( $table );
256
257 return $titleArray->count();
258 }
259
260 /**
261 * Partition the backlinks into batches.
262 * Returns an array giving the start and end of each range. The firsti
263 * batch has a start of false, and the last batch has an end of false.
264 *
265 * @param $table String: the links table name
266 * @param $batchSize Integer
267 * @return Array
268 */
269 public function partition( $table, $batchSize ) {
270
271 // 1) try this per process cache first
272
273 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
274 wfDebug( __METHOD__ . ": got from partition cache\n" );
275 return $this->partitionCache[$table][$batchSize]['batches'];
276 }
277
278 $this->partitionCache[$table][$batchSize] = false;
279 $cacheEntry =& $this->partitionCache[$table][$batchSize];
280
281
282 // 2) try full result cache
283
284 if ( isset( $this->fullResultCache[$table] ) ) {
285 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
286 wfDebug( __METHOD__ . ": got from full result cache\n" );
287
288 return $cacheEntry['batches'];
289 }
290
291
292 // 3) ... fallback to memcached ...
293
294 global $wgMemc;
295
296 $memcKey = wfMemcKey(
297 'backlinks',
298 md5( $this->title->getPrefixedDBkey() ),
299 $table,
300 $batchSize
301 );
302
303 $memcValue = $wgMemc->get( $memcKey );
304
305 if ( is_array( $memcValue ) ) {
306 $cacheEntry = $memcValue;
307 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
308
309 return $cacheEntry['batches'];
310 }
311
312
313 // 4) ... finally fetch from the slow database :(
314
315 $this->getLinks( $table );
316 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
317 // Save to memcached
318 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
319
320 wfDebug( __METHOD__ . ": got from database\n" );
321 return $cacheEntry['batches'];
322 }
323
324 /**
325 * Partition a DB result with backlinks in it into batches
326 * @param $res database result
327 * @param $batchSize integer
328 * @return array @see
329 */
330 protected function partitionResult( $res, $batchSize ) {
331 $batches = array();
332 $numRows = $res->numRows();
333 $numBatches = ceil( $numRows / $batchSize );
334
335 for ( $i = 0; $i < $numBatches; $i++ ) {
336 if ( $i == 0 ) {
337 $start = false;
338 } else {
339 $rowNum = intval( $numRows * $i / $numBatches );
340 $res->seek( $rowNum );
341 $row = $res->fetchObject();
342 $start = $row->page_id;
343 }
344
345 if ( $i == $numBatches - 1 ) {
346 $end = false;
347 } else {
348 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
349 $res->seek( $rowNum );
350 $row = $res->fetchObject();
351 $end = $row->page_id - 1;
352 }
353
354 # Sanity check order
355 if ( $start && $end && $start > $end ) {
356 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
357 }
358
359 $batches[] = array( $start, $end );
360 }
361
362 return array( 'numRows' => $numRows, 'batches' => $batches );
363 }
364 }